package fhp.hlhj.giantfold.fragment


import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcDetailPage
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.lzy.okgo.model.HttpParams
import fhp.hlhj.giantfold.Contents

import fhp.hlhj.giantfold.R
import fhp.hlhj.giantfold.activity.malls.TBOrderListAty
import fhp.hlhj.giantfold.interfaces.IGoodsFgm
import fhp.hlhj.giantfold.adapter.SuperMarketRcyAdp
import fhp.hlhj.giantfold.customView.FullyGridLayoutManager
import fhp.hlhj.giantfold.customView.FullyLinearLayoutManager
import fhp.hlhj.giantfold.javaBean.ErroBean
import fhp.hlhj.giantfold.javaBean.SuperMarketListBean
import fhp.hlhj.giantfold.javaBean.TypesBean
import fhp.hlhj.giantfold.network.Urls
import fhp.hlhj.giantfold.presenter.SuperMarketListPresenter
import fhp.hlhj.giantfold.utils.LogUtil
import fhp.hlhj.giantfold.utils.PageHelper
import kotlinx.android.synthetic.main.fragment_all_goods_fgm.view.*
import java.util.HashMap

/**
 * A simple [Fragment] subclass.
 */
class AllGoodsFgm : Fragment(), IGoodsFgm {

    private var layoutType=1
    private lateinit var rootView: View
    private lateinit var listViewAdp: SuperMarketRcyAdp
    private var INSTENCE: AllGoodsFgm? = null
    private lateinit var type: TypesBean.DataBean
    private var index=-1
    private lateinit var goodsPresenter:SuperMarketListPresenter
    private lateinit var nextPageUrl:String
    private lateinit var pageHelper:PageHelper<SuperMarketListBean.DataBean>
    private var page=1
    private var datas=ArrayList<SuperMarketListBean.DataBean>()
    companion object {
        fun newInstece(type: TypesBean.DataBean,indext:Int): AllGoodsFgm {
            val allGoodsFgm = AllGoodsFgm()
            val bundle = Bundle()
            bundle.putSerializable("data", type)
            bundle.putInt("index",indext)
            allGoodsFgm.arguments = bundle
            return allGoodsFgm
        }
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.fragment_all_goods_fgm, container, false)
        type = arguments.getSerializable("data") as TypesBean.DataBean
        index=arguments.getInt("index")
        LogUtil.log("获得传餐" + type.classname)
        listViewAdp= SuperMarketRcyAdp(R.layout.supermarket_listitem,datas,activity)
        rootView.recyclerview.adapter=listViewAdp

        /**
         * 设置加载
         */
        val loadView = LayoutInflater.from(context).inflate(R.layout.loadmore, null)
        listViewAdp.addFooterView(loadView)
        listViewAdp.setOnItemClickListener { adapter, view, position ->
           /*打开领券详情*/
            val quanStr = datas[position].quan_link
            var quanStrs = quanStr.split("activity_id=")
            if (quanStrs.size==1)quanStrs=quanStr.split("activityId=")
            val activityId= quanStrs[1]
            val page = AlibcPage(Urls.TK_QUAN_URL+"activityId=$activityId&itemId=${datas[position].goods_id}&pid=mm_116147303_36832537_132678582")
            LogUtil.log(Urls.TK_QUAN_URL+"activityId=$activityId&itemId=${datas[position].goods_id}")
            val showParams = AlibcShowParams(OpenType.H5, false)
            val params = AlibcTaokeParams()
            params.pid="mm_116147303_36832537_132678582"
//            params.adzoneid="132678582"
            params.subPid="mm_116147303_36832537_132678582"
            params.extraParams = HashMap<String, String>()
            params.extraParams.put("taokeAppkey","24624369")
            LogUtil.log("成功设置的pid为，${params.pid}")
            AlibcTrade.show(activity,page,showParams,params,null,object :AlibcTradeCallback{
                override fun onFailure(p0: Int, p1: String?) {
                    LogUtil.log("错误$p1")
                }
                override fun onTradeSuccess(p0: AlibcTradeResult) {
                    LogUtil.log("成功${p0.payResult.paySuccessOrders[0]}设置的pid为，${params.pid}")
                    if (null!=p0.payResult.paySuccessOrders&&p0.payResult.paySuccessOrders.size>0) {
                        val intent = Intent(context, TBOrderListAty::class.java)
                        intent.putExtra("pid",datas[position].goods_id)
                        intent.putExtra("et",5)
                        intent.putExtra("rate",datas[position].rate)
                        intent.putExtra("imgurl",datas[position].pic)
                        context.startActivity(intent)
                    }

                }
            })
            /*打开商品详情*/
            /*val showParams = AlibcShowParams(OpenType.Native, false)
            val params = AlibcTaokeParams()
            params.pid="mm_116147303_36832537_132678582"
//            params.adzoneid="132678582"
            params.subPid="mm_116147303_36832537_132678582"
            val detailPage = AlibcDetailPage(datas[position].goods_id)
            LogUtil.log("成功设置的pid为，${params.pid}")
            AlibcTrade.show(activity,detailPage,showParams,params,null,object :AlibcTradeCallback{
                override fun onFailure(p0: Int, p1: String?) {
                    LogUtil.log("失败$p1")
                }

                override fun onTradeSuccess(p0: AlibcTradeResult) {
                    LogUtil.log("成功${p0.payResult.paySuccessOrders[0]}设置的pid为，${params.pid}")
                    if (null!=p0.payResult.paySuccessOrders&&p0.payResult.paySuccessOrders.size>0){
//                        商品详情
                        val intent = Intent(context, TBOrderListAty::class.java)
                        intent.putExtra("pid",datas[position].goods_id)
                        intent.putExtra("et",5)
                        intent.putExtra("rate",datas[position].rate)
                        intent.putExtra("imgurl",datas[position].pic)
                        startActivity(intent)
                    }

                }
            })*/
        }

        goodsPresenter=SuperMarketListPresenter(this)

        rootView.recyclerview.isNestedScrollingEnabled = false
//        rootView.recyclerview.layoutManager=FullyLinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        rootView.recyclerview.layoutManager=LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)


//        rootView.recyclerview.layoutManager=LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        val params=HttpParams()
        params.put("appkey",Contents.TKAPPKEY)
        params.put("type","classify")
        params.put("cid",type.id)
        params.put("page",page)
        goodsPresenter.getGoods(params)
        return rootView
    }

    override fun showLoading() {
        LogUtil.log("开始获得列表数据")
    }

    /**
     * 获取数据
     */
    @RequiresApi(Build.VERSION_CODES.M)
    override fun getGoods(data: SuperMarketListBean) {
        pageHelper=PageHelper(data.data,10)
        datas.addAll(pageHelper.currentList())
        listViewAdp.notifyDataSetChanged()
        LogUtil.logi("进入了吗？${data.data.size}")
//        listViewAdp.notifyDataSetChanged()

    }
    public fun nextPage(){
        LogUtil.logi("执行这个方法")
        try {
            if (pageHelper!=null){
                if (pageHelper.hasNextPage()){
                    pageHelper.nextPage()
                    datas.addAll(pageHelper.currentList())
                    listViewAdp.notifyDataSetChanged()

                }else{

                }
            }
        }catch (e:Exception){

        }


    }
    public fun smooth(){
        rootView.recyclerview.scrollToPosition(0)
    }
    private fun findMax(lastPositions: IntArray): Int {
        var max = lastPositions[0]
        for (value in lastPositions) {
            if (value > max) {
                max = value
            }
        }
        return max
    }
    /**
     * 改变布局
     */
    override fun changeLayout() {
        if (layoutType==1){
            rootView.recyclerview.layoutManager=FullyGridLayoutManager(context,2)
            layoutType=2
        }else{
            rootView.recyclerview.layoutManager=FullyLinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
            layoutType=1
        }
    }

    /**
     * 筛选
     */
/*    override fun filter(data: List<SuperMarketListBean.ProListBean.DataBean>) {
    }*/
    override fun onError(erro: ErroBean) {
    }

    /**
     * 加载下一页
     */
    override fun setLoadmorde() {
    }
/*    override fun loadNextPage(data: List<SuperMarketListBean.ProListBean.DataBean>) {
    }*/
}